package com.os.osframe.scaffold.velocity;

import com.os.osframe.scaffold.domain.ScaffoldXmlField;
import com.os.osframe.scaffold.domain.ScaffoldXmlTable;
import com.os.osframe.scaffold.util.*;

import java.io.*;
import java.util.*;

/**
 * Created by wangdc on 2018-4-27.
 */
public class CreateCode {


    protected Map paramMap=new HashMap();


    protected ScaffoldXmlTable scaffoldXmlTable;


    protected PropertyConfigurerLoader propertyConfigurer;
    public PropertyConfigurerLoader getPropertyConfigurer(){
        if(propertyConfigurer==null){
            propertyConfigurer= (PropertyConfigurerLoader) SpringUtils.getBean("propertyConfigurer");
        }
        return propertyConfigurer;
    }
    public CreateCode(){

    }
    public CreateCode(ScaffoldXmlTable scaffoldXmlTable){
        this.scaffoldXmlTable=scaffoldXmlTable;
    }
    /**
     * 待替换变量
     * @param packages 模块包路径
     */
    protected Map getParams(String packages){

        //获取包简称
        String packagesSimple=null;
        String[] packagesSimpleArr=packages.split("\\.");

        for(int i=0;i<packagesSimpleArr.length;i++){
            if(StringUtil.isNull(packagesSimple)){
                packagesSimple=packagesSimpleArr[i];
            }else{
                packagesSimple+=packagesSimpleArr[i].substring(0, 1).toUpperCase()+packagesSimpleArr[i].substring(1);
            }
        }

        String packagesPath=packages.replaceAll("\\.","/");
        paramMap.put("pageType", (String) getPropertyConfigurer().getProperty("osframe.auto.page.type"));
        paramMap.put("packages",packagesSimple);
        paramMap.put("packagesPath",packagesPath);
        paramMap.put("author", (String) getPropertyConfigurer().getProperty("osframe.auto.author"));
        paramMap.put("time", DateUtil.convertDate2String(DateUtil.DATETIME_FORMAT, new Date()));
        if(scaffoldXmlTable!=null) {
            paramMap.put("entity", scaffoldXmlTable.getDomain());
            paramMap.put("entityVar", scaffoldXmlTable.getDomain().substring(0, 1).toLowerCase() + scaffoldXmlTable.getDomain().substring(1));
            paramMap.put("table", scaffoldXmlTable.getTableName());
            paramMap.put("info", scaffoldXmlTable.getTableInfo());
            paramMap.put("jspEntityTitle", scaffoldXmlTable.getTableInfo());
            paramMap.put("template",scaffoldXmlTable.getTemplate());

            List<ScaffoldXmlField> scaffoldXmlFieldList =scaffoldXmlTable.getScaffoldXmlFieldList();
            List fieldsList=new ArrayList();
            if(scaffoldXmlFieldList!=null){
                for(ScaffoldXmlField scaffoldXmlField:scaffoldXmlFieldList){
                    String fieldLabel=scaffoldXmlField.getFiledName();
                    String tableField=scaffoldXmlField.getFiledId();
                    boolean fieldIsNull=false;
                    String fieldLength=scaffoldXmlField.getFiledLength();
                    String fieldType=scaffoldXmlField.getJavaType();
                    String fieldName=scaffoldXmlField.getFiledId();
                    String javaFieldMax=fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);

                    Map fieldMap=new HashMap();
                    fieldMap.put("fieldLabel",fieldLabel);
                    fieldMap.put("tableField",tableField);
                    fieldMap.put("fieldIsNull",fieldIsNull);
                    if(StringUtil.isNotNull(fieldType) && "String".equals(fieldType)){//只针对字符串设置长度
                        if(fieldLength==null || "".equals(fieldLength)){
                            fieldLength="200";
                        }
                        fieldMap.put("fieldLength",fieldLength);
                    }else{
                        fieldMap.put("fieldLength","");
                    }
                    fieldMap.put("fieldType",fieldType);
                    fieldMap.put("fieldIsNull",fieldIsNull);
                    fieldMap.put("javaFieldMax",javaFieldMax);
                    fieldMap.put("fieldName",fieldName);
                    fieldsList.add(fieldMap);
                }
            }
            paramMap.put("fieldList", fieldsList);
        }
        return paramMap;
    }
    /**
     *  生成文件
     * @param sourcePath
     * @param tempPath
     * @param targetPath
     * @throws Exception
     */
    public void createFile(String sourcePath,String tempPath,String targetPath)throws  Exception{
        System.out.println("正在生成文件：" + tempPath + " -> " + targetPath);
        File tempFile = new File(sourcePath+tempPath);
        File targetFile =null;
        if(".vm".equals(targetPath.substring(targetPath.length() - 3))){
            targetFile = new File(targetPath.substring(0,targetPath.length() - 3));
        }else{
            targetFile = new File(targetPath);
        }

        if (tempFile.isDirectory()) {
            Boolean bool=targetFile.mkdirs();//直接进入到多层子集导致没有目录而创建失败
            System.out.println("创建文档："+bool);
            String[] files = tempFile.list();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].startsWith("."))
                        continue;
                    //替换文件名
                    String fileName=files[i].replaceAll("\\$entity\\$",(String)paramMap.get("entity"));
                    fileName=fileName.replaceAll("\\$packagesPath\\$",(String)paramMap.get("packagesPath"));
                    fileName=fileName.replaceAll("\\$entityVar\\$", (String) paramMap.get("entityVar"));
                    createFile(sourcePath,tempPath + "/" + files[i], targetPath + "/"+ fileName);
                }
            }
        } else if(tempFile.isFile() && !tempFile.isHidden()) {
            String parseStr=VelocityParse.getInstance().parseTemplate(tempPath, paramMap);
            BufferedWriter output = null;
            targetFile.createNewFile();
            output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
            output.write(parseStr);
            output.close();
        }
    }

    /**
     * 直接根据模板生成文件
     * @param packages
     * @throws Exception
     */
    public void create(String packages)throws Exception{
        System.out.println("=====开始生成文件=====");
        String basePath = (String) getPropertyConfigurer().getProperty("osframe.file.path");//获取属性配置的服务器路径
        if (basePath.substring(basePath.length() - 1).equals("/")) {
            basePath = basePath.substring(basePath.length() - 1);
        }
        String targetFilePath=basePath;
        targetFilePath+="/auto/code/"+packages.replaceAll("\\.","/");
        //System.out.println(targetFilePath);
        String sourcePath=new File(this.getClass().getResource("").getPath()).getAbsolutePath();
        int lindex=sourcePath.lastIndexOf("/classes/");
        sourcePath=sourcePath.substring(0,lindex+9);
        String tempKey=(String)paramMap.get("template");
        if(tempKey==null || "".equals(tempKey)){
            tempKey=(String) getPropertyConfigurer().getProperty("osframe.auto.default.template");
            if(tempKey==null || "".equals(tempKey)){
                tempKey="velocityTemp";
            }
        }
        if(tempKey==null || "".equals(tempKey)) {
            System.out.println("=====未找到模板文件，停止生成代码=====");
            return;
        }
        String tempPath="template/"+tempKey;
        createFile(sourcePath,tempPath,targetFilePath);
    }


}
